package cn.stylefeng.guns.modular.wx.mp.controller;

import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.modular.demos.entity.BizWxUser;
import cn.stylefeng.guns.modular.demos.model.params.BizWxUserParam;
import cn.stylefeng.guns.modular.demos.model.result.BizWxUserResult;
import cn.stylefeng.guns.modular.demos.service.BizWxUserService;
import cn.stylefeng.guns.modular.wx.mp.config.WxMpConfiguration;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.RoleService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import javax.annotation.Resource;
import javax.xml.ws.Action;

/**
 * @author Edward
 */
@Slf4j
@AllArgsConstructor
@Controller
@RequestMapping("/wx/redirect/{appid}")
public class WxRedirectController {
    private final WxMpService wxService;
    
    
    @Autowired
    private BizWxUserService bizWxUserService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;
    
	@Resource
	private AuthService authService;
    

    @RequestMapping("/greet")
    public String greetUser(@PathVariable String appid, @RequestParam String code, ModelMap map) {
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        map.put("code", code);
        try {
            WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
            log.info("accessToken={}", JSON.toJSONString(accessToken));
            WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);

            Long sysUserId = null;
            Long wxUserId = null;
            
            ///
            BizWxUserParam param = new BizWxUserParam();
            param.setWxOpenId(user.getOpenId());
           
            
            BizWxUserResult  bizWxUser = bizWxUserService.findBySpec(param);
            if(bizWxUser == null) {
            	BizWxUser entity = new BizWxUser();
            	entity.setWxOpenId(user.getOpenId());
            	bizWxUserService.saveOrUpdate(entity);
            	bizWxUser = bizWxUserService.findBySpec(param);
            }
            
            sysUserId = bizWxUser.getUserId();
            wxUserId = bizWxUser.getId();
            
            map.put("wxUserId", wxUserId);
            
            if(sysUserId!=null) {
            	User sysUser = userService.getById(bizWxUser.getUserId());
            	String token = authService.login(sysUser.getAccount());
            	map.put("token",token);
            	//获取角色
            	String roleIds = sysUser.getRoleId();
            	String[] roleIdArr = roleIds.split(",");
            	String roles = "";
            	for(String id : roleIdArr) {
            		roles += roleService.getById(String.valueOf(id)).getDescription();
            	}
            	map.put("roles",roles);
            	map.put("realName",sysUser.getName());
            }
            log.info("wxMpUser={}", JSON.toJSONString(user));
            //map.put("user", user);
          
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return  "/mh5/index.html";
       // return "greet_user";
    }
    
 

}
